<?php
declare (strict_types = 1);

namespace app\controller\notify;

use app\BaseController;
use app\exception\NotifyException;
use app\helpers\UtilHelper;
use app\model\Notify;
use app\model\Orders;
use app\model\Shops;
use app\model\ShopsPayment;
use think\facade\Queue;
use think\helper\Arr;
use think\helper\Str;
use think\Request;

class NotifyController extends BaseController
{

    //异步通知
    public function notify(Request $request,$channel)
    {
        $log = Notify::saveParams(0,$request->all(),Notify::TYPE_NOTIFY,0);
        try {
            $channel = ucfirst(strtolower($channel));
            $notifyClass = sprintf("app\controller\\notify\\Notify%s",$channel);
            $notifyClass = new \ReflectionClass($notifyClass);
            $class = $notifyClass->newInstance();
            $order = $class->notify($request);
            if($order){
                $log->order_id = $order->id;
                $log->pay_method = $order->pay_method;
                $log->save();
            }
        }catch (NotifyException $e){
           tplog("异步通知错误: ",['msg'=>$e->getMessage(),'trace'=>$e->getTraceAsString()],'notify');
           $order = $e->getOrder();
           if($order->isExists()) {
               Orders::saveExceptionMessage($order,$e->getMessage());
               if($order->is_repurchase)  Orders::pushShopifyOrder($order->pid);
           }
        }
        return match (strtoupper($channel)) {
            'ASIABILL', 'ADYEN' => 'success',
            default => json(['code' => 200, 'msg' => 'success']),
        };
    }


    public function checkout(Request $request,Orders $order)
    {
        $host = $order->shop->website ?: $order->shop->host;
        $host = domain($host);
        $loading_path = $request->param('loading_path');
        $return_path = $request->param('return_path');
        $loading_path = urldecode($loading_path);
        $return_path = urldecode($return_path);
        $query = $request->all();
        $query['order_id'] = $order->id;
        $query = Arr::except($query,['loading_path','return_path','success']);
        $query = array_filter($query,function ($value){
            return !empty($value);
        });
        try{
            $service = match ($order->pay_method){
                ShopsPayment::PAY_METHOD_ASIABILL => new NotifyAsiabill(),
                ShopsPayment::PAY_METHOD_STRIPE => new NotifyStripe(),
                ShopsPayment::PAY_METHOD_PAYONEER => new NotifyPayoneer(),
                default => new NotifyPaypal(),
            };
            $flag = $request->param('success','false');
            if($flag == 'false') throw new \Exception("customer cancel pay");
            $service->capture($request,$order);
            $splitor = Str::contains($loading_path,'?') ? '&' : "?";
            $query = Arr::only($query,['order_id']);
            $url = sprintf('%s/%s%s%s',$host,ltrim($loading_path,'/'),$splitor,UtilHelper::buildQueryString($query));
            return redirect(domain($url));
        }catch (\Exception $e){
            if($order->is_repurchase)  Orders::pushShopifyOrder($order->pid);//完成首单
            $query['error'] = $e->getMessage();
            $splitor = Str::contains($return_path,'?') ? '&' : "?";
            $url = sprintf('%s/%s%s%s',$host,ltrim($return_path,'/'),$splitor,UtilHelper::buildQueryString($query));
            return redirect(domain($url));
        }
    }



}
